import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout'
const whiteList = ['/login', '/404', '/401']

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/index'),
        meta: { title: '首页' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'),
    meta: { title: '登录' }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach(async (to, from, next) => {
  // 取消所有请求，可选
  const CancelToken = axios.CancelToken
  store.getters.source.cancel && store.getters.source.cancel()
  store.commit('app/SET_SOURCE', CancelToken.source())
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const userInfo = store.getters.userInfo
      if (userInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/logout')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
